package com.itheima.health.filter;


import com.alibaba.fastjson.JSON;
import com.itheima.health.common.GlobalConst;
import com.itheima.health.common.MessageConst;
import com.itheima.health.config.PermissionMap;
import com.itheima.health.entity.Result;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 登录过滤器
 *
 * @author liCuiPing
 * @since 2022/11/1 10:04
 */
@Slf4j
@Component
//urlPatterns 属性为 过滤器要拦截的路径
@WebFilter(urlPatterns="/*",filterName = "loginCheckFilter")
public class LoginCheckFilter implements Filter {
    @Autowired
    private PermissionMap permissionMap;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        log.info("已到达过滤器");
        /*
         * 判断 对要放行的直接放行
         * 不直接放行的判断  有没有登录成功操作  即session有没有值
         * */
        //得到 请求的 uri
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("application/json; charset=UTF-8");
        String requestURI = request.getRequestURI();     //得到了uri
        //加入 可直接放行的集合数组
        String[] uri = {
                "/user/login",
                "/user/logout",
                "/user/getUsername",
                "/common/**",
                "/mobile/**",      // 移动端的无需登录都可以访问接口
        };
        //判断请求的路径 在不在  直接放行的集合数组之内
        //使用路径匹配器,   可以匹配 /**    这种字符路径
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String item : uri) {
            //如果匹配成功,会返回true
            boolean match = antPathMatcher.match(item, requestURI);
            if (match) {
                //判断成功,放行
                filterChain.doFilter(request,response);
                return;
            }
        }

        // 后端进入 不能直接访问 开始鉴权操作
        //判断登录状态
        //用户拥有的登录权限集合
        List<String> keyWordList = (List) request.getSession().getAttribute(GlobalConst.USER_PERMISSION);
        if (keyWordList != null) {
            //已登录过
            //判断该路径是否需要权限
            Map<String, String>permissionMaps = permissionMap.getMaps();
            for (Map.Entry<String, String> entry : permissionMaps.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                //判为true即路径需要权限
                if (antPathMatcher.match(key, requestURI)) {
                    //判断用户是否拥有此路径的权限
                    if (keyWordList.contains(value)) {
                        //存在,放行
                        filterChain.doFilter(request, response);
                        return;
                    }
                    //不存在,返回
                    response.getWriter().write(JSON.toJSONString(new Result(false, "没有权限")));
                    return;
                }
            }
            //路径无需权限,直接可访问
            filterChain.doFilter(request,response);
            return;
        }

        //进入未登录
        //返回未登录的错误信息
        response.setContentType("application/json; charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(new Result(false, MessageConst.LOGIN_NO)));
    }
}